
clear all
clear matrix
set more off
set maxvar 30000
set matsize 1000

local path_load 	= "00_data/01_datasets/00_inputs"
local path_save 	= "00_data/01_datasets/01_results"
local path_FTmain 	= "03_figures_tables/01_Main"


local Controls_Variables = "dlnVIX dlnSP  dlnEEM"
local Years_Sample       = "0 2007 2010"

local do_OLS 	= 1
local do_EStudy = 1

foreach sample_year in `Years_Sample' {   // Loop for sample years
forval window_type =0/1               {   // Loop for different event windows (0 is the baseline 2-day window)

	*** Load dataset
		global window_type = `window_type'
		use "`path_load'/03_BreakEvenInflation.dta", clear
		qui sort Date
		qui gen date_id = _n
		qui sort date_id
		qui tset date_id

	*** Change in the BE rate
		qui gen BE_Change   = (BE-L.BE)
		qui label variable BE_Change "BE Change, pp"

	***	Log-variation in Argentine EMBI
		qui gen EMBI_ARG_Change   = 100*(ln(EMBI_ARG)-ln(L.EMBI_ARG))
		qui label variable EMBI_ARG_Change "EMBI % Change, pp"
		
	***	Log-variation in Argentine Stock Index (Merval)
		qui gen Merval_Change   = 100*(ln(Merval_px)-ln(L.Merval_px))
		qui label variable Merval_Change "Merval % Change, pp"

	** Define the LHS variable (ARG EMBI or Merval)
		if "EMBI_ARG_Change" == "EMBI_ARG_Change" {
		qui gen DepVar_Change = EMBI_ARG_Change
		}
		else if "EMBI_ARG_Change" == "Merval_Change" {
		qui gen DepVar_Change = Merval_Change
		}

	*** Merge with global controls dataset
		qui merge 1:1 Date using "`path_load'/01_GlobalFactors_Controls.dta"
		qui keep if _merge==3
		qui drop _merge
		qui sort date_id

	*** Compute % changes for the global factors
		qui foreach ii in "VIX_CLOSE" "SP_CLOSE" "EEM_CLOSE"{
		gen dln`ii' = 100*(`ii'-L.`ii')/L.`ii'
		replace  dln`ii' = . if  dln`ii'==0
		replace  dln`ii' = . if  dln`ii'>20
		replace  dln`ii' = . if  dln`ii'<-20
		}
		qui rename dlnVIX_CLOSE dlnVIX
		qui rename dlnSP_CLOSE dlnSP
		qui rename dlnEEM_CLOSE dlnEEM

	*** Keep sample period
		if `sample_year' == 2007 {
			qui keep if (Date>=d(01jan2007)  & Date<=d(01mar2008))
		}
		if `sample_year' == 2010 {
			qui keep if (Date>=d(01jan2010)  & Date<=d(01mar2011))
		}
		if `sample_year' == 0 {
		    qui keep if (Date>=d(01jan2007)  & Date<=d(01mar2011))
		}

	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// CREATE EVENT WINDOWS
	do "01_codes/00_CreateWindows_fx.do"
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	


	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	* OLS REGRESIONS: 2007 & 2010
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		if `do_OLS'==1 & `sample_year'>0 {

		     qui matrix Sample_OLS    = J(3,5,.)
			 forval i=1(1)3 { 
				 if `i'==1{
				 * Full sample
				 reg DepVar_Change BE_Change  `Controls_Variables', robust
				 }
				 if `i'==2{
				 * Only event days
				 reg DepVar_Change BE_Change  `Controls_Variables' if in_window==1, robust
				 }
				 if `i'==3{
				 * Only non-event days
				 reg DepVar_Change BE_Change  `Controls_Variables' if out_window==1, robust
				 }
				 * Store results
				 qui matrix aa1 =  e(V) 
				 qui scalar se_tmp = sqrt(aa1[1,1])
				 qui matrix Sample_OLS[`i',1] = _b[BE_Change]         						 // coefficient
				 qui matrix Sample_OLS[`i',2] = se_tmp                	 	                 // standard error
				 qui matrix Sample_OLS[`i',3] = (_b[BE_Change]/se_tmp) 			             // t-stat
		         qui matrix Sample_OLS[`i',4] = (2 * ttail(e(N), abs(_b[BE_Change]/se_tmp))) // two-sided p-val
				 qui matrix Sample_OLS[`i',5] = e(N)             			                 // number of observations
			 }	
				
			* Store results in .dta file
			preserve
				clear
				svmat  double Sample_OLS, name(var)
				rename var1  beta
				rename var2  se
				rename var3  tstat
				rename var4  pval
				rename var5  obs
				gen Labels = ""
				replace Labels = "Full Sample"      if _n==1
				replace Labels = "Event Days"       if _n==2
				replace Labels = "Non-Event Days"   if _n==3
				order Labels, first
		    save  "`path_save'/30_OLS_Regression_FullSample_Window_`window_type'_Year_`sample_year'.dta", replace
			restore
		}
	//------------------------------------------------------------------------------   


	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	* OLS REGRESIONS: ROLLING WINDOW
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		if `do_OLS'==1 & `sample_year'==0 & `window_type'==0 {

		preserve

		rolling _b _se N=e(N), window(300) step(30)  keep(Date) clear: regress DepVar_Change  i.in_window#c.BE_Change `Controls_Variables',robust
		gen Date = date-date[1]+d(01jan2007)
					format Date %td
					rename _stat_1   betas_coef_NE
					rename _stat_7   betas_NE_se
					rename _stat_2   betas_coef
					rename _stat_8   betas_se
					gen ind=0
					replace ind=1 if betas_coef==.
					replace betas_coef = . if _eq2_N<50
				* CI
				scalar sig1   = 0.05
			    gen CI_upper  = betas_coef + invnormal(1-sig1/2)*betas_se
				gen CI_lower  = betas_coef - invnormal(1-sig1/2)*betas_se 
						
				twoway (rarea CI_upper CI_lower  Date, cmissing(n) ///
				fcolor(gs12) fintensity(20)  lcolor(white)   ) ///
			    (function y=0,   range(Date)      clcolor(fg)  lwidth(thin) lpattern(dash))  ///
				(line betas_coef Date,  cmissing(n) ///
				lpattern(solid) lcolor(black) msymbol(O) msize(small) mlcolor(black) mcolor(black) lwidth(medthick)) /// 
				(line betas_coef_NE Date, ///
				lpattern(dash) lcolor(black) msymbol(O) msize(small) mlcolor(black) mcolor(black) lwidth(med)), /// 
			   	tlabel(01jan2007  01jan2008 01jan2009  01jan2010, format(%tdCY)) ///	
				title("", color(black) size(medsmall)) ///
				ytitle("Coeff", size(medsmall)) xtitle("Date", size(medsmall)) ///
				graphregion(color(white)) plotregion(color(white)) bgcolor(white) ///
				ylabel(, nogrid labsize(medsmall)) ///
				legend(off) name(betas_coeffs, replace)
			    qui graph export "`path_FTmain'/OLS_RollingWindows_Window_`window_type'.pdf", replace

    	restore
		}
	//------------------------------------------------------------------------------	



	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	* EVENT STUDY APPROACH
	///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	if `do_EStudy'==1 & `window_type'==0 &`sample_year'!=0  { 

		* Create matrix to store all results
		qui matrix Event_Study    = J(3,6,.)
 
		preserve
		
		*Exclude days with large changes in global factors
		*Results are similar but slightly noisier with these obs
		foreach ii in "dlnVIX" "dlnSP"  "dlnEEM" {
		qui replace  `ii'  = . if  `ii'> 10
		qui replace  `ii'  = . if  `ii'<-10
		}
		
		* Compute Abnormal Returns
		reg EMBI_ARG_Change dlnVIX dlnSP  dlnEEM, robust
		predict Abnormal_Return, residuals	

			* Compute mean BE_Change for each window
			bysort EVENT_ID: egen BE_Cum = mean(BE_Change)
			replace BE_Cum =. if EVENT_ID==0
			
			* Sort windows across 2 categories: Good news & Bad news
			sum BE_Change if out_window==1,detail
			qui gen EVENT_TYPE  = .
			qui replace EVENT_TYPE = 1 if BE_Cum>r(mean)                  // Good News
		    qui replace EVENT_TYPE = 3 if BE_Cum<=r(mean)                 // Bad News   
			qui replace EVENT_TYPE = 2 if EVENT_TYPE!=1 & EVENT_TYPE!=3   // No News [empty]
			qui replace EVENT_TYPE = . if in_window==0

			* Compute means & the J statistic (for each category);  J-stat=Abnormal Return / sd * sqrt(number of obs)
			qui summarize Abnormal_Return if out_window==1
			qui scalar sd_AR_out = r(sd)

			foreach i in 1 2 3 {
			summarize Inf_Misreport_Change if (in_window==1 & EVENT_TYPE==`i')
				qui scalar Misreport_`i'   = r(mean)
			summarize BE_Change if (in_window==1 & EVENT_TYPE==`i')
				qui scalar BE_`i'          = r(mean)
			summarize Abnormal_Return if (in_window==1 & EVENT_TYPE==`i')
				qui scalar mean_ar_`i'     = r(mean)
				qui scalar cum_ar_`i'      = r(sum)
				qui scalar obs_`i'         = r(N)
				qui scalar ttest_`i'       = cum_ar_`i' / (sqrt(obs_`i') * sd_AR_out)
				scalar li ttest_`i'

			* Store results
			matrix Event_Study[`i', 1] = obs_`i'
			local window_size = 2
			matrix Event_Study[`i', 2] = ceil(obs_`i'/`window_size') // Number of events
			matrix Event_Study[`i', 3] = mean_ar_`i'                 // Mean Abnormal Return
			matrix Event_Study[`i', 4] = ttest_`i'                   // J statistic
			matrix Event_Study[`i', 5] = BE_`i'                      // Mean Change in BE
			matrix Event_Study[`i', 6] = Misreport_`i''              // Mean Change in Inflation Misreport
			}
			
			* Store Results in .dta file
			clear
		    svmat  double Event_Study, name(var)
			rename var1 Obs
			rename var2 Events
			rename var3 AR_mean
			rename var4 Jstat
			rename var5 BE_mean
			rename var6 Misreport
			gen Event_Type = ""
			replace Event_Type = "Good News" if _n==1
			replace Event_Type = "No News"   if _n==2   // [empty]
			replace Event_Type = "Bad News"  if _n==3
			order Event_Type, first
		    save "`path_save'/40_EventStudy_Window_`window_type'_Year_`sample_year'.dta", replace
		restore
	matrix li Event_Study
	}
	
	*--------------------------------------------------------------------------------------
	 

}
}

